package com.dhcc.bpm.modules.scf.util;

import com.dhcc.bpm.modules.scf.entity.IdCard.IdCardBack;
import com.dhcc.bpm.modules.scf.entity.IdCard.IdCardJust;
import com.dhcc.bpm.modules.scf.entity.OcrResult;
import com.dhcc.bpm.modules.scf.entity.ScfSubjectBasicInfo;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class OCRUtil {

    /**
     * @param fileBase64 文件字节流
     * @param fileType   文件类型
     * @return ocrResult
     */
    public OcrResult getOcr(String fileBase64, String fileType, String ak, String sk, String projectId, String endpoint) {
        OcrResult ocrResult = new OcrResult();
        ScfSubjectBasicInfo scfSubjectBasicInfo = new ScfSubjectBasicInfo();
        IdCardJust idCardJust = new IdCardJust();
        IdCardBack idCardBack = new IdCardBack();
        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        // 默认连接超时时间为60秒，可根据需要调整
        config.withTimeout(60);
        // 根据需要配置是否跳过SSL证书验证
        // 执行SDK时出现javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure报错，可添加此代码，跳过SSL证书验证
        config.withIgnoreSSLVerification(true);
        // 指定终端节点，以OCR服务北京四的 endpoint 为例
        // 初始化客户端认证信息，需要填写相应 projectId/domainId，以初始化 BasicCredentials 为例
        BasicCredentials basicCredentials = new BasicCredentials()
                .withAk(ak)
                .withSk(sk)
                .withProjectId(projectId);
        // 初始化指定云服务的客户端 {Service}Client ，以初始化 Region 级服务OCR的 OcrClient 为例
        OcrClient client = OcrClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(basicCredentials)
                .withEndpoint(endpoint)
                .build();
        if (fileType.equals("businessLicense")) {
            // 营业照识别接口 RecognizeBusinessLicenseRequest
            RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
            BusinessLicenseRequestBody body = new BusinessLicenseRequestBody();
            body.withImage(fileBase64);
            request.withBody(body);
            try {
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy年MM月dd日");
                RecognizeBusinessLicenseResponse response = client.recognizeBusinessLicense(request);
                System.out.println(response.toString());
                BusinessLicenseResult result = response.getResult();
                scfSubjectBasicInfo.setIdNum(result.getRegistrationNumber());
                scfSubjectBasicInfo.setSubName(result.getName());
                // 定义数字模式的正则表达式
                String regex = "\\d+(\\.\\d+)?";

                // 创建 Pattern 对象
                Pattern pattern = Pattern.compile(regex);

                // 创建 Matcher 对象
                Matcher matcher = pattern.matcher(result.getRegisteredCapital());
                double number = 0;
                // 查找匹配的数字
                if (matcher.find()) {
                    String numberStr = matcher.group();
                    number = Double.parseDouble(numberStr);
                }
                BigDecimal RegisteredCapital = new BigDecimal(number);
                scfSubjectBasicInfo.setRegisteredCapital(RegisteredCapital);
                // 主体类型暂时不填充，需要用户手动选择类型
                // scfSubjectBasicInfo.setUnitType(result.getType());
                scfSubjectBasicInfo.setLegalName(result.getLegalRepresentative());
                String businessTerm = null;
                try {
                    BigDecimal capital = new BigDecimal(result.getRegisteredCapital().replaceAll("[^\\d.]", ""));
                    scfSubjectBasicInfo.setRegisteredCapital(capital);
                    String foundDate = result.getFoundDate();
                    Date startDate = inputFormat.parse(foundDate);
                    String startDateString = startDate.toString();
                    scfSubjectBasicInfo.setRegisteredDate(startDateString);
                    businessTerm = result.getBusinessTerm();
                } catch (Exception e) {
                    scfSubjectBasicInfo.setRegisteredCapital(null);
                    scfSubjectBasicInfo.setRegisteredDate(null);
                    businessTerm = null;
                }
                try {
                    String endDateString =businessTerm.equals("长期") ?"长期": businessTerm.substring(12);
                    Date endDate;
                    if (endDateString.equals("长期")) {
                        endDate = inputFormat.parse("2099年12月31日");
                        scfSubjectBasicInfo.setExpirationDate(String.valueOf(endDate));
                    } else {
                        endDate = inputFormat.parse(endDateString);
                        scfSubjectBasicInfo.setExpirationDate(String.valueOf(endDate));
                    }
                } catch (ParseException | NullPointerException e) {
                    scfSubjectBasicInfo.setExpirationDate(null);
                }
                scfSubjectBasicInfo.setBusinessScope(result.getBusinessScope());
                scfSubjectBasicInfo.setRegisteredAddr(result.getAddress());
            } catch (ConnectionException | RequestTimeoutException e) {
                scfSubjectBasicInfo.setBusinessScope(null);
                scfSubjectBasicInfo.setRegisteredAddr(null);
            } catch (ServiceResponseException e) {
                scfSubjectBasicInfo.setRegisteredCapital(null);
                scfSubjectBasicInfo.setLegalName(null);
            }
        }
        if (fileType.equals("corporateIdPhoto")) {
            // 身份证识别接口 RecognizeIdCardRequest
            RecognizeIdCardRequest request = new RecognizeIdCardRequest();
            IdCardRequestBody body = new IdCardRequestBody();
            body.withImage(fileBase64);
            request.withBody(body);
            try {
                RecognizeIdCardResponse response = client.recognizeIdCard(request);
                System.out.println(response.toString());
                IdCardResult result = response.getResult();
                idCardJust.setSubName(result.getName());
                idCardJust.setIdNum(result.getNumber());

            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
        if (fileType.equals("individualIdPhoto")) {
            // 身份证识别接口 RecognizeIdCardRequest
            RecognizeIdCardRequest request = new RecognizeIdCardRequest();
            IdCardRequestBody body = new IdCardRequestBody();
            body.withImage(fileBase64);
            request.withBody(body);
            try {
                RecognizeIdCardResponse response = client.recognizeIdCard(request);
                System.out.println(response.toString());
                IdCardResult result = response.getResult();
                idCardJust.setSubName(result.getName());
                idCardJust.setBirthday(result.getBirth());
                String sex = result.getSex();
                if (sex != null) {
                    if (sex.equals("男")) {
                        idCardJust.setSex("1");
                    } else if (sex.equals("女")) {
                        idCardJust.setSex("0");
                    }
                }
                idCardJust.setIdNum(result.getNumber());
                idCardJust.setAddress(result.getAddress());
                idCardBack.setAgency(result.getIssue());
                idCardBack.setIdDate(result.getValidTo());

            } catch (ConnectionException | RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
        ocrResult.setScfSubjectBasicInfo(scfSubjectBasicInfo);
        ocrResult.setIdCardJust(idCardJust);
        ocrResult.setIdCardBack(idCardBack);
        return ocrResult;
    }
}